﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraSplashScreen;
using System.IO;
using DevExpress.XtraEditors;

namespace DevExpress.MailClient.Win.Forms
{
    public partial class frmStartScanning : PRO_DOCS.BLL.WIN.Templates.DevxPermissionTemplate
    {
        List<string> CURRENT_ARCHIVES_COPYING_FOLDERS
        {
            get;
            set;
        }

        PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE cURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE;
        PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE CURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE
        {
            get { return cURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE; }
            set
            {
                cURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE = value;
                this.Text = string.Format("Scan to folder \"{0}\" ...", cURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME);
                txtFolderName.Text = cURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_NAME;
            }
        }
        public frmStartScanning(PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE _cURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE)
        {
            InitializeComponent();
            CURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE = _cURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE;

        }

        bool document_scanned = false;
        string NEW_SCANNED_FILE_PATH = string.Empty;
        private void tsbScanFile_Click(object sender, EventArgs e)
        {
            document_scanned = scanningCtrl1.StartScan();
            tsbSaveFile.Enabled = document_scanned;
            if (document_scanned)
            {
                NEW_SCANNED_FILE_PATH = scanningCtrl1.NEW_SCANNED_FILE_PATH;
            }
        }

        Dictionary<int, PRO_DOCS.DAL.Database.ARCHIVE_DOCUMENT_TYPE> ARCHIVE_DEPARTMENT_DOCUMENT_TYPES
        { get; set; }
        PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE CURRENT_ARCHIVE_DEPARTMENT_FILE
        { get; set; }
        PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY
        { get; set; }
        private void tsbSaveFile_Click(object sender, EventArgs e)
        {
            dxErrorProvider1.ClearErrors();

            bool continueSaving = !string.IsNullOrEmpty(txtDocumentName.Text) && comboDocumentTypes.SelectedIndex > -1;

            if (continueSaving)
            {
                bool fileIndeciesValid = new PRO_DOCS.BLL.WIN.CustomDataTypes().VALIDATE_DYNAMIC_INDECIES_INPUT_VALUES(tblDynamicInfos, dxErrorProvider1);

                if (fileIndeciesValid)
                {
                    bool FILES_ADDED = false;

                    DevExpress.MailClient.Win.Data.UploadedPhysicalFiles uploadedPhysicalFiles = new Data.UploadedPhysicalFiles();
                    uploadedPhysicalFiles.CheckedFile = true;
                    uploadedPhysicalFiles.FileId = Guid.NewGuid();
                    uploadedPhysicalFiles.FileInfo = new FileInfo(NEW_SCANNED_FILE_PATH);
                    uploadedPhysicalFiles.UploadingMessage = string.Empty;
                    uploadedPhysicalFiles.CurrentIcon = "none";

                    FILE_UPLOADED = false;
                    //1. Copy the file to the Folder
                    if (uploadedPhysicalFiles.CheckedFile)
                    {
                        //the new fileId to be named with
                        string newCreatedPhysicalFileName = uploadedPhysicalFiles.FileId.ToString();
                        //the original file path
                        FileInfo currentConsumedFile = uploadedPhysicalFiles.FileInfo;
                        //a. copy the file

                        for (int fc = 0; fc < CURRENT_ARCHIVES_COPYING_FOLDERS.Count; fc++)
                        {
                            try
                            {
                                currentConsumedFile.CopyTo(Path.Combine(CURRENT_ARCHIVES_COPYING_FOLDERS[fc], newCreatedPhysicalFileName));
                                FILE_UPLOADED = true;
                                break;
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }

                        if (FILE_UPLOADED)
                        {
                            //2. ADD the file table
                            CURRENT_ARCHIVE_DEPARTMENT_FILE = new PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE();
                            CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID = Guid.NewGuid();
                            //--------->aRCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID = aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID = CURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NAME = txtDocumentName.Text; //currentConsumedFile.Name.Replace(currentConsumedFile.Extension, string.Empty);
                            CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NOTES = txtNotes.Text;
                            //---------->get the document type
                            CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DOCUMENT_TYPE_ID = ARCHIVE_DEPARTMENT_DOCUMENT_TYPES[comboDocumentTypes.SelectedIndex].ARCHIVE_DOCUMENT_TYPE_ID;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_GENERATED_BARCODE_VALUE = PRO_DOCS.BLL.WIN.Utilities.FileType.GenerateRandomBarcode();
                            CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_CREATION_DATE = DateTime.Now;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_IS_LOCKED = false;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE.IS_DELETED = false;

                            PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_FILESInsert
                                (
                                CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID,
                                CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE_ID.Value,
                                CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_CREATION_DATE.Value,
                                PRO_DOCS.BLL.WIN.Authentication.LOGGED_IN_EMPLOYEE_DETAILS.LOGIN_USER.LOGIN_USER_ID,
                                CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NAME,
                                CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DOCUMENT_TYPE_ID.Value,
                                CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_GENERATED_BARCODE_VALUE,
                                CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_DISPLAY_NOTES,
                                CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_IS_LOCKED.Value,
                                CURRENT_ARCHIVE_DEPARTMENT_FILE.IS_DELETED.Value
                                );

                            //1. ADD The file history
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY = new PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY();
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID = uploadedPhysicalFiles.FileId;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ID = CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID;
                            //aRCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID = Guid.NewGuid();
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_CHANGING_TYPE_ID = 1;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ORIGINAL_NAME = currentConsumedFile.Name;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_EXTENSION = currentConsumedFile.Extension;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_BY_USER_ID = PRO_DOCS.BLL.WIN.Authentication.LOGGED_IN_EMPLOYEE_DETAILS.LOGIN_USER.LOGIN_USER_ID;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_FILE_SIZE = currentConsumedFile.Length;
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_DATE = DateTime.Now;

                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.IS_DELETED = false;


                            PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_FILE_HISTORYInsert
                            (
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID,
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ID.Value,
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_CHANGING_TYPE_ID.Value,
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_ORIGINAL_NAME,
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_EXTENSION,
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_BY_USER_ID.Value,
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_UPLOADED_DATE.Value,
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_FILE_SIZE.Value,
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_NOTES,
                            CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.IS_DELETED.Value);

                            SAVE_SELECTED_FILE_DYNAMIC_INDICIES();

                            FILES_ADDED = true;
                        }
                        else
                        {
                            XtraMessageBox.Show("There was error copying the file to the destination folder, please make sure that there is enough desk space or you are connected the network path successfully.");
                        }

                        FILE_UPLOADED = FILE_UPLOADED && FILES_ADDED;

                        if (FILE_UPLOADED)
                        {
                            this.Close();
                        }
                    }
                }
            }
            else
            {
                if (string.IsNullOrEmpty(txtDocumentName.Text))
                {
                    dxErrorProvider1.SetError(txtDocumentName, PRO_DOCS.BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "document Name"), XtraEditors.DXErrorProvider.ErrorType.Information);
                }

                if (comboDocumentTypes.SelectedIndex.Equals(-1))
                {
                    dxErrorProvider1.SetError(comboDocumentTypes, PRO_DOCS.BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "document type"), XtraEditors.DXErrorProvider.ErrorType.Information);
                }
            }
        }

        private void frmStartScanning_Load(object sender, EventArgs e)
        {
            #region DOCUMENT TYPES FOR THE CURRENT DEPARTMENT

            ARCHIVE_DEPARTMENT_DOCUMENT_TYPES = new Dictionary<int, PRO_DOCS.DAL.Database.ARCHIVE_DOCUMENT_TYPE>();
            List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_DOCUMENT_TYPE> cURRENT_DOCUMENT_FILES = CURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_DOCUMENT_TYPEs.ToList();

            comboDocumentTypes.Properties.Items.BeginUpdate();
            comboDocumentTypes.Properties.Items.Clear();
            int nmbr = 0;
            for (int i = 0; i < cURRENT_DOCUMENT_FILES.Count; i++)
            {
                if (!cURRENT_DOCUMENT_FILES[i].IS_DELETED.Value)
                {
                    ARCHIVE_DEPARTMENT_DOCUMENT_TYPES.Add(nmbr, cURRENT_DOCUMENT_FILES[i].ARCHIVE_DOCUMENT_TYPE);
                    comboDocumentTypes.Properties.Items.Add(cURRENT_DOCUMENT_FILES[i].ARCHIVE_DOCUMENT_TYPE.ARCHIVE_DOCUMENT_TYPE_NAME);
                    nmbr++;
                }
            }

            comboDocumentTypes.Properties.Items.EndUpdate();
            comboDocumentTypes.SelectedIndex = -1;
            #endregion
        }

        PRO_DOCS.DAL.Database.ARCHIVE_DOCUMENT_TYPE ARCHIVE_DOCUMENT_TYPE
        { get; set; }



        internal PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY SAVE_SELECTED_FILE_DYNAMIC_INDICIES()
        {
            bool fileIndeciesValid = new PRO_DOCS.BLL.WIN.CustomDataTypes().VALIDATE_DYNAMIC_INDECIES_INPUT_VALUES(tblDynamicInfos, dxErrorProvider1);


            PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY cURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY = null;

            if (fileIndeciesValid)
            {


                Guid aRCHIVE_DEPARTMENT_FILE_HISTORY_ID = Guid.NewGuid();
                bool fileSaved = false;
                if (CURRENT_ARCHIVE_DEPARTMENT_FILE != null)
                {
                    if (!CURRENT_ARCHIVE_DEPARTMENT_FILE.ARCHIVE_DEPARTMENT_FILE_ID.Equals(Guid.Empty))
                    {
                        Dictionary<Guid, string> gET_DYNAMIC_INDECIES_INPUT_VALUES = new PRO_DOCS.BLL.WIN.CustomDataTypes().GET_DYNAMIC_INDECIES_INPUT_VALUES(tblDynamicInfos);

                        #region SAVE IF THE FILE IS 1st TIME SAVING
                        //if (CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUEs.Count.Equals(0))
                        {
                            aRCHIVE_DEPARTMENT_FILE_HISTORY_ID = CURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID;

                            SAVE_FILE_HISTORY_DYNAMIC_INDECIES(aRCHIVE_DEPARTMENT_FILE_HISTORY_ID, gET_DYNAMIC_INDECIES_INPUT_VALUES);

                            fileSaved = true;
                        }
                        #endregion



                    }
                }

            }
            else
            {
                XtraMessageBox.Show("Saving cannot be completed because some required field left blank,\r\nPlease set values for these indecies before continue", "Saving Truncated", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            return cURRENT_ARCHIVE_DEPARTMENT_FILE_HISTORY;
        }
        private void SAVE_FILE_HISTORY_DYNAMIC_INDECIES(Guid aRCHIVE_DEPARTMENT_FILE_HISTORY_ID, Dictionary<Guid, string> gET_DYNAMIC_INDECIES_INPUT_VALUES)
        {
            //1. save the file baseic data

            //2. save the file dynamic data
            foreach (KeyValuePair<Guid, string> dYNAMIC_INDECIES_INPUT_VALUE in gET_DYNAMIC_INDECIES_INPUT_VALUES)
            {
                PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE aRCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE = new PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE();

                aRCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE.ARCHIVE_DEPARTMENT_FILE_HISTORY_INDEX_VALUE_ID = Guid.NewGuid();
                aRCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE.ARCHIVE_DEPARTMENT_DOCUMENT_TYPE_INDEX_ID = dYNAMIC_INDECIES_INPUT_VALUE.Key;
                aRCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID = aRCHIVE_DEPARTMENT_FILE_HISTORY_ID;
                aRCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE.ARCHIVE_DEPARTMENT_FILE_HISTORY_INDEX_VALUE = dYNAMIC_INDECIES_INPUT_VALUE.Value;

                PRO_DOCSDatabaseDataContext.proc_ARCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUESInsert
                    (
                        aRCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE.ARCHIVE_DEPARTMENT_FILE_HISTORY_INDEX_VALUE_ID,
                        aRCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE.ARCHIVE_DEPARTMENT_DOCUMENT_TYPE_INDEX_ID,
                        aRCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE.ARCHIVE_DEPARTMENT_FILE_HISTORY_ID,
                        aRCHIVE_DEPARTMENT_FILE_HISTORY_INDEXES_VALUE.ARCHIVE_DEPARTMENT_FILE_HISTORY_INDEX_VALUE
                    );

            }
        }


        private void comboDocumentTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboDocumentTypes.SelectedIndex > -1)
            {
                bool CONTINUE_UPLOADING = false;

                CURRENT_ARCHIVES_COPYING_FOLDERS = new List<string>();

                ARCHIVE_DOCUMENT_TYPE = ARCHIVE_DEPARTMENT_DOCUMENT_TYPES[comboDocumentTypes.SelectedIndex];

                new PRO_DOCS.BLL.WIN.CustomDataTypes().GET_DOCUMENT_TYPE_STRUCTURE(tblDynamicInfos, ARCHIVE_DOCUMENT_TYPE);

                List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHE> aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES = CURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHy.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHEs.ToList();

                for (int i = 0; i < aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES.Count; i++)
                {
                    if (new DirectoryInfo(aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES[i].ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH).Exists)
                    {
                        CONTINUE_UPLOADING = true;
                        CURRENT_ARCHIVES_COPYING_FOLDERS.Add(aRCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHES[i].ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH);
                    }
                }

                MessageBox.Show("FINISHED GET PATHES");

                if (!CONTINUE_UPLOADING)
                {
                    XtraMessageBox.Show
                        (
                            string.Format("The storage media for the \"{0}\" department was not found.{1}Please make sure that you are connected to the network or contact your network administrator", CURRENT_ARCHIVE_DEPARTMENTS_FOLDERS_STRUCTURE.ARCHIVE_DEPARTMENT.ARCHIVE_DEPARTMENT_NAME, Environment.NewLine),
                            "Storage Media was not found",
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Warning
                        );

                    tsbSaveFile.Enabled = false;
                }
            }
        }

        public bool FILE_UPLOADED { get; set; }
    }
}
